import time
import sys
import platform
from PyQt5.QtWidgets import QApplication
from voice_assistant.ui.floating_window import FloatingMicWindow
from voice_assistant.ui.tray_icon import create_qt_tray_icon  # 需要适配为Qt托盘
from voice_assistant.voice.microphone import VoiceRecorder
from voice_assistant.ws.ws_client import run_async_websocket
from voice_assistant.com_utils import setup_logging, run_in_thread

logger = setup_logging()

class MainApplication(QApplication):
    def __init__(self, sys_argv):
        super().__init__(sys_argv)
        self.floating_window = None
        self.tray_icon = None
        self.recorder = None
        
    def initialize(self):
        """初始化应用程序"""
        # 创建悬浮窗口
        self.floating_window = FloatingMicWindow()
        self.floating_window.show()
        
        # 创建系统托盘图标
        self.tray_icon = create_qt_tray_icon(self)
        if self.tray_icon:
            logger.info("已创建系统托盘图标")
            self.tray_icon.show()
        
        # 启动录音
        self.recorder = VoiceRecorder()
        self.recorder.start()
        
        # 启动WebSocket连接
        def delayed_start():
            time.sleep(1)  # 等待1秒，让界面先显示
            run_async_websocket()

        run_in_thread(delayed_start)
        
        logger.info("语音助手客户端已启动，等待唤醒...")
    
    def shutdown(self):
        """安全关闭应用程序"""
        logger.info("正在关闭应用程序...")
        if self.recorder:
            self.recorder.stop()
        sys.exit(0)

def main():
    """应用程序主函数"""
    # 设置DPI感知
    if platform.system() == "Windows":
        try:
            from ctypes import windll
            windll.shcore.SetProcessDpiAwareness(1)
            logger.info("已设置DPI感知")
        except Exception as e:
            logger.error(f"DPI感知设置失败: {str(e)}")
    try:
        app = MainApplication(sys.argv)
        app.initialize()
        sys.exit(app.exec_())
    except KeyboardInterrupt:
        logger.info("程序已退出")
        sys.exit(0)
    except Exception as e:
        logger.error(f"致命错误: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())
        sys.exit(1)

if __name__ == "__main__":
    main()